/*
 * Copyright (C), 2002-2016, 苏宁易购电子商务有限公司
 * FileName: ResponseAspect.java
 * Author:   admin
 * Date:     2016年3月15日 上午10:40:14
 * Description: //模块目的、功能描述      
 * History: //修改记录
 * <author>      <time>      <version>    <desc>
 * 修改人姓名             修改时间            版本号                  描述
 */
package com.suning.app.snpaasadmin.util;


import com.suning.app.snpaasadmin.action.ClusterManagementAction;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * 〈一句话功能简述〉<br> 
 * 〈功能详细描述〉
 *
 * @author admin
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Aspect    
@Component    
public  class ResponseAspect {    
    private Logger logger = Logger.getLogger(ResponseAspect.class);
    //本地异常日志记录对象    
     //private  static  final Logger logger = LoggerFactory.getLogger(SystemLogAspect. class);    
    
    //Service层切点    
    //@Pointcut("@annotation(com.suning.app.snpaasserver.util.SystemServiceLog)")    
    @Pointcut("execution(* com.suning.app.snpaasadmin.action..*.*(..))")
     public  void serviceAspect() {    
    }    
    
    //Controller层切点    
//    @Pointcut("@annotation(com.suning.app.snpaasadmin.util.SystemControllerLog)")    
//     public  void controllerAspect() {    
//     }    
    
    @SuppressWarnings("rawtypes")
    @Around("serviceAspect()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        Object object = null;
        String methodName = pjp.getSignature().getName();
        try{
            object = pjp.proceed();
            logger.fatal("The method " + methodName + " begins with " + Arrays.asList(pjp.getArgs()));
        }catch(Throwable e){
            logger.fatal("The method " + methodName + " occurs expection : " + e);
            logger.fatal(e);
            logger.fatal(e.getCause());
            logger.fatal(e.getMessage());
            object = "success";
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("success", false);
            Class[] argsClass = new Class[1]; ;
            argsClass[0] = dataMap.getClass();
            if (pjp.getTarget() instanceof ClusterManagementAction) {
                logger.fatal("taget");
            }
            if(pjp.getThis() instanceof ClusterManagementAction){
                logger.fatal("this");
            }
            Method method = pjp.getTarget().getClass().getMethod("setDataMap", Map.class);
            method.invoke(pjp.getTarget(), dataMap);
            throw new RuntimeException(e);
        }
        return object;
    }

    /**  
     * 异常通知 用于拦截service层记录异常日志  
     *  
     * @param joinPoint  
     * @param e  
     */
    @AfterThrowing(pointcut = "serviceAspect()", throwing = "e")    
     public  void doAfterThrowing(JoinPoint joinPoint, Throwable e) {  
        //获取用户请求方法的参数并序列化为JSON格式字符串    
        String params = "";    
         if (joinPoint.getArgs() !=  null && joinPoint.getArgs().length > 0) {    
             for ( int i = 0; i < joinPoint.getArgs().length; i++) {    
                params += JsonUtil.convertToJson(joinPoint.getArgs()[i]) + ";";    
            }    
        }  
         StringWriter sw = new StringWriter();
         PrintWriter pw = new PrintWriter(sw);
         try {    
              /*========控制台输出=========*/    
            logger.fatal("=====异常通知开始=====");
            logger.fatal("exception:"+e);
            e.printStackTrace(pw);
            logger.fatal(sw.toString());
            logger.fatal("异常详情：" + e.fillInStackTrace());
            logger.fatal("异常代码:" + e.getClass().getName());    
            logger.fatal("异常信息:" + e.getMessage());   
            logger.fatal("异常源头："+e.getCause());
            logger.fatal("长度："+e.getStackTrace().length);
            logger.fatal("异常方法:" + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()"));    
            //System.out.println("方法描述:" + getServiceMthodDescription(joinPoint));     
            logger.fatal("请求参数:" + params);    
               /*==========数据库日志=========*/    
            logger.fatal("=====异常通知结束=====");    
        }  catch (Exception ex) {    
            //记录本地异常日志    
            logger.error("==异常通知异常==");   
            logger.fatal(ex);
        }    
         /*==========记录本地异常日志==========*/    
        //logger.error("异常方法:{}异常代码:{}异常信息:{}参数:{}", joinPoint.getTarget().getClass().getName() + joinPoint.getSignature().getName(), e.getClass().getName(), e.getMessage(), params);    
   
    }    
}